The constructor must be named Car
, the same as the name of the class.
The constructor is used when an object is constructed.
Most of the work in constructing an object is automatically done by the Java system.
Usually you need to write only a few statements that initialize a instance variables.
The constructor for Car
will initialize the three variables
of the object.
The parameter list of a constructor looks like this:
dataType parameterName , dataType parameterName , and so on
Each dataType is the type of one item of data that will be handed to the constructor, and each parameterName is a name that is used for that item of data.
Here is the class definition, with the constructor partially finished:
class Car { // instance variables double startMiles; // Stating odometer reading double endMiles; // Ending odometer reading double gallons; // Gallons of gas used between the readings // constructor Car( , , ) { } // methods }
Fill in the blanks in the parameter list. The data type of each parameter should match the data type of an instance variable. The names of the parameters are up to you.